package medium;

public class Trie {

    Trie[] tries = new Trie[26];

    boolean end = false;

    /**
     * Initialize your data structure here.
     */
    public Trie() {

    }

    /**
     * Inserts a word into the trie.
     */
    public void insert(String word) {
        Trie trie = this;
        for (int i = 0; i < word.length(); i++) {
            trie.tries[word.charAt(i) - 'a'] = trie.tries[word.charAt(i) - 'a'] == null?new Trie():
                    trie.tries[word.charAt(i) - 'a'];
            trie = trie.tries[word.charAt(i) - 'a'];
        }
        trie.end = true;
    }

    /**
     * Returns if the word is in the trie.
     */
    public boolean search(String word) {
        Trie trie = this;
        for (int i = 0; i < word.length(); i++) {
            Trie trie1 = trie.tries[word.charAt(i) - 'a'];
            if(trie1 == null) return false;
            trie = trie1;
        }
        return trie.end;
    }

    /**
     * Returns if there is any word in the trie that starts with the given prefix.
     */
    public boolean startsWith(String prefix) {
        Trie trie = this;
        for (int i = 0; i < prefix.length(); i++) {
            Trie trie1 = trie.tries[prefix.charAt(i) - 'a'];
            if(trie1 == null) return false;
            trie = trie1;
        }
        return true;
    }
}

/**
 * Your Trie object will be instantiated and called as such:
 * Trie obj = new Trie();
 * obj.insert(word);
 * boolean param_2 = obj.search(word);
 * boolean param_3 = obj.startsWith(prefix);
 */